package com.audaque.springboot.foshanupload.doc.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-08 16:03:44
 */
public class MultipartFileUtil {
    public static MultipartFile getMulFileByPath(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        File f = new File(filePath);
        String fieldName = f.getName();
        FileItem fileItem = factory.createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true,
                fieldName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = fileItem.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    public static MultipartFile getMultipartFileByFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    public static String uploadToPath(MultipartFile fileUpload) throws IOException {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID() + suffixName;
        //指定本地文件夹存储图片
        String fileDir = "E:\\";
        String path = fileDir + fileName;
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File upload_file = new File(path);
        fileUpload.transferTo(upload_file);
        return path;
    }

}
